/***************************************************************************
 *                                                                          *
 * Copyright (c) 2013 Corefaster Elec & Tech Corp.         *
 *	All rights reserved.        				   *
 *                                                                          *
 ****************************************************************************/ 

/****************************************************************************
 * 
 * FILENAME
 *   vehiclestatus.c
 *
 * VERSION
 *     1.0
 *
 * DESCRIPTION
 *     This file is a program used to Check OBD Interface Status and OBD
 * voltage
 *   OBD voltage is located at nIRQ[0]/GPIO[16]
 *   Interface voltage is located at nIRQ[1]/GPIO[17]

 *
 * DATA STRUCTURES
 *     None
 *
 * FUNCTIONS
 *     None
 *
 * HISTORY
 *     01/25/2014            Ver 1.0 Created by Ray Gu
 *
 * REMARK
 *     None
 **************************************************************************/

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

#define GPIO_CFG5 		0xFFF83050
#define GPIO_DIR5 		0xFFF83054
#define GPIO_DATAOUT5 	0xFFF83058
#define GPIO_DATAIN5		0xFFF8305C


void SetPowerGPIO()
{
	unsigned int reg;
	//set GPIO16 work as GPIO
	reg = *(volatile unsigned int *)(GPIO_CFG5);			
	*(volatile unsigned int *)(GPIO_CFG5) = reg & 0xFF3FFFFF;
	//set GPIO16 enable pull-up resisiter
	reg = *(volatile unsigned int *)(GPIO_DIR5);			
	*(volatile unsigned int *)(GPIO_DIR5) = reg | 0x08000000;
	//set GPIO16 input mode
	reg = *(volatile unsigned int *)(GPIO_DIR5);		
	*(volatile unsigned int *)(GPIO_DIR5) = reg & 0xFFFFF7FF;
	printf("Power Detection is Changed to GPIO\n");

}

void SetPowerIRQ()
{
	unsigned int reg;
	//set GPIO16 work as IRQ0
	reg = *(volatile unsigned int *)(GPIO_CFG5);			
	*(volatile unsigned int *)(GPIO_CFG5) = reg |  0x0040000;
	printf("Power Detection is Changed to IRQ0\n");
}

unsigned char GetPowerStatus()
{
	unsigned int reg;
	reg = *(volatile unsigned int *)(GPIO_DATAIN5);
	if(reg & 0x00000800)
		return 0;
	else
		return 1;
}

void SetInterfaceGPIO()
{
	unsigned int reg;
	//set GPIO17 work as GPIO
	reg = *(volatile unsigned int *)(GPIO_CFG5);			
	*(volatile unsigned int *)(GPIO_CFG5) = reg & 0xFCFFFFFF;
	//set GPIO17 enable pull-up resisiter
	reg = *(volatile unsigned int *)(GPIO_DIR5);			
	*(volatile unsigned int *)(GPIO_DIR5) = reg | 0x10000000;
	//set GPIO17 input mode
	reg = *(volatile unsigned int *)(GPIO_DIR5);		
	*(volatile unsigned int *)(GPIO_DIR5) = reg & 0xFFFFEFFF;
	printf("Interface is Changed to GPIO\n");

}

void SetInterfaceIRQ()
{
	unsigned int reg;
	//set GPIO17 work as IRQ0
	reg = *(volatile unsigned int *)(GPIO_CFG5);			
	*(volatile unsigned int *)(GPIO_CFG5) = reg | 0x01000000;
	printf("Interface is Changed to IRQ0\n");
}

unsigned char GetInterfaceStatus()
{
	unsigned int reg;
	reg = *(volatile unsigned int *)(GPIO_DATAIN5);
	if(reg & 0x00001000)
		return 0;
	else
		return 1;
}
